<?php
/**
 * File: ConsoleController.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 13:56
 */

namespace Command\Controller;

use Think\Controller;

/**
 * 命令入口文件
 * @package Command\Controller
 */
class ConsoleController extends Controller
{
    const ExitOK = 0;
    const ExitFAIL = 1;

    protected $route;
    protected $param;
    protected $defaultAction = 'index';
    protected $controller;
    protected $action;

    /**
     * 初始化方法
     */
    public function init()
    {
        $this->parseParam();
        $route = $this->parseRoute();
        if (!$route) {
            echo "提示：请输入要执行的命令 [controller/action]" . PHP_EOL;
            return self::ExitOK;
        }
        if (A($this->controller) === false) {
            echo "提示：控制器'{$this->controller}'不存在" . PHP_EOL;
            return self::ExitFAIL;
        }
        //调用控制器方法
        R($this->controller . '/' . $this->action, $this->param);
        return self::ExitOK;
    }

    /**
     * 解析命令行参数
     */
    protected function parseParam()
    {
        $param = json_decode(getenv('TP_PARAM'), true);
        $this->route = $param[1];
        $this->param = array_slice($param, 2);
    }

    /**
     * 解析路由
     */
    protected function parseRoute()
    {
        if (empty($this->route)) {
            return false;
        }
        $reg = '/^([a-z]+)\\/?([a-z]*)$/';;
        $res = preg_match($reg, strtolower($this->route), $route);
        if (!$res) {
            return false;
        }
        $this->controller = $route[1];
        $this->action = empty($route[2]) ? $this->defaultAction : $route[2];

        return true;
    }
}
